package com.jbh.apilibrary.api

import com.google.gson.Gson
import okhttp3.*
import retrofit2.GsonConverterFactory
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit


class ApiRequest {

    private val okHttpClient = OkHttpClient.Builder()
        .cookieJar(MyCookieJar())
        .connectTimeout(6, TimeUnit.MINUTES)
        .readTimeout(6, TimeUnit.MINUTES)
        .writeTimeout(6, TimeUnit.MINUTES)


    private val retrofit = Retrofit.Builder()
        .baseUrl(Api.HOST)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())


    /**
     * @param serviceClass
     * @param <S>
     * @return
    </S> */
    @Synchronized
    fun <S> createService(serviceClass: Class<S>?): S {
        okHttpClient.apply {
            interceptors()
            addInterceptor(HttpInterceptor())
        }

        return retrofit
            .apply { client(okHttpClient.build()) }
            .build()
            .create(serviceClass)
    }




    /**
     *
     */
    inner class HttpInterceptor : Interceptor {

        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val builder = chain.request().newBuilder()
            val request = builder
//                .addHeader("Cookie", "loginUserName=yxj02")
//                .addHeader("Cookie", "loginUserPassword=000000")
//                .addHeader("Content-type", "application/json")
//                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build()
            return chain.proceed(request)
        }
    }



    companion object{

        fun createService(): ApiInterface {
            return ApiRequest().createService(ApiInterface::class.java)
        }

        /**
         * @param map
         * @return
         */
        fun getPostContentRequestBody(map: HashMap<String, Any>): RequestBody {
            val content = Gson().toJson(map)
            println("[post] -> content = $content")
            return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), content)
        }



        fun post(netUrl:String ,paramsMap: HashMap<String, Any>){

            val builder = FormBody.Builder();
            for (key in paramsMap) {
                //追加表单信息
                builder.add(key.key, key.value .toString())
            }

            val formBody: RequestBody = builder.build()
            val request = Request.Builder()
                .url(netUrl)
                .post(formBody)
                .build()

            val okHttpClient = OkHttpClient.Builder().build()

            okHttpClient.newCall(request).enqueue(object :Callback{
                    override fun onResponse(call: Call?, response: Response?) {
                        println("[onResponse] - > ${String(response!!.body().bytes())}")
                    }
                    override fun onFailure(call: Call?, e: IOException?) {
                        println("[onResponse] - > ${e?.message}")
                    }
            })
        }
    }
}